package middleware

import (
	"net/http"
)

// CommonJwtAuthMiddleware : with jwt on the verification, no jwt on the verification
type CorsMiddleware struct {
}

func NewCommonJwtAuthMiddleware() *CorsMiddleware {
	return &CorsMiddleware{}
}

func (m *CorsMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		query := r.URL.Query()
		stream := query["stream"][0]
		// 0表示正常 1表示流化
		if stream == "1"{
			w.Header().Set("Content-Type", "text/event-stream; charset=utf-8")
			w.Header().Set("Cache-Control", "no-cache")
			w.Header().Set("Connection", "keep-alive")
		}
		// 流式 输出
		w.Header().Set("Access-Control-Allow-Origin", "*")

		// 如果是预检请求，直接返回
		if r.Method == "OPTIONS" {
			w.WriteHeader(http.StatusOK)
			return
		}
		// 调用下一个处理函数
		next.ServeHTTP(w, r)
	}
}
